#!/bin/bash

add_vlan() {
  local dev_name=$1
  local vrf_id=$2
  local vlan_ip_mask=$3
	sudo ip link add link $dev_name name vlan$vrf_id type vlan id $vrf_id
	sudo ip link set vlan$vrf_id up
	sudo ip addr add $vlan_ip dev vlan$vrf_id 
}

add_vrf() {
  local vrf_id=$1
  # vrf的table id和vrf名并无关系，此处为了方便，统一使用vrf_id作为table id
	sudo ip link add vrf$vrf_id type vrf table $vrf_id
	sudo ip link set vrf$vrf_id up
}

vlan_bind_vrf() {
  local vlan_name=$1
  local vrf_name=$2 
	sudo ip link set $vlan_name master $vrf_name
}

add_vlan_vrf() {
  local dev_name=$1
  local vlan_id=$2
  local vlan_ip=$3
  local vrf_id=$vlan_id
  add_vlan $dev_name $vrf_id $vlan_ip
  add_vrf $vrf_id
  vlan_bind_vrf vlan$vrf_id vrf$vrf_id
}

if [ $# -lt 1 ]; then
  echo "err! Usage: $0 help"
  exit 1
fi

if [ $1 == "help" ]; then
  echo "Usage: $0 [add/del] vlan_id vlan_ip/mask dev_name"
  echo "Example: $0 add 10 10.0.1.10/24 ens33"
  exit 0
elif [ $1 == "add" ]; then
  if [ $# -lt 4 ]; then
    echo "err! Usage: $0 add vlan_id vlan_ip/mask dev_name"
    exit 1
  fi
  vlan_id=$2
  vlan_ip_mask=$3
  dev_name=$4
  sudo ip link set $dev_name up
  add_vlan_vrf $dev_name $vlan_id $vlan_ip_mask
elif [ $1 == "del" ]; then
  if [ $# -lt 3 ]; then
    echo "err! Usage: $0 del vlan_id"
    exit 1
  fi
  sudo ip link del vlan$2
  sudo ip link del vrf$2
  exit 0
else
  echo "err! Usage: $0 [add/del]"
  exit 1
fi

